package com.demo.webapp.ui.paging;

import javax.servlet.ServletContext;

import com.demo.webapp.ui.config.ComponentRulesModule;
import com.demo.webapp.ui.displayer.DisplayerMapping;
import com.demo.webapp.ui.paging.PageRepositoryBuilder;
import com.demo.webapp.ui.paging.PageRepositoryResource;
import com.demo.webapp.ui.RepositoryBuilderBase;

/**
 * Page组件的持久化对象生成器类
 * 
 * @author ryuu.kk
 *
 */
public class PageRepositoryBuilder extends RepositoryBuilderBase {

	/**
	 * 默认文件装载策略配置文件
	 */
	public static final String[] REPOSITORY_PAGE_BASENAME = {"classpath:com/demo/webapp/ui/paging/digester-page.xml"};
	
	private PageRepositoryResource pageRepository;
	
	/**
	 * 初始化MenuRepositoryBuilder数据
	 */
	private void init() {
		if (pageRepository == null) {
			pageRepository = new PageRepositoryResource();
		}
		
		//使用默认配置文件位置
		if (getBaseNames() == null || getBaseNames().length ==0) {
			setBaseNames(PageRepositoryBuilder.REPOSITORY_PAGE_BASENAME);
		}
	}
	
	@Override
	public void beforeLoad(ComponentRulesModule module) {
		//数据初始化
		init();
		
		//设置栈顶对象,XML文件将操作这个对象将属性注入
		push(this.pageRepository);
		log.debug(module);
	}

	@Override
	public void afterLoad(ServletContext servletContext) {
		log.debug("after load.");
		DisplayerMapping mapping = this.pageRepository.getMapping();
		if (mapping != null) {
			/* 未开发Velocity的Displayer对象
			List<DisplayerConfig> dispConfigs = mapping.getDisplayerConfig();
			if (dispConfigs != null && dispConfigs.size() > 0) {
				for (DisplayerConfig config : dispConfigs) {
					if ("com.demo.webapp.ui.menu.displayer.VelocityMenuDisplayer".equals(config.getType())) {
						if (this.servletContext == null) {
					        log.error("ServletContext not set - can't initialize Velocity");
						} else {
							VelocityMenuDisplayer.initialize(this.servletContext);
						}
					}
				}
			}*/
		}
        //将持久对象MenuRepositoryResource放入Servlet容器上下文中
		servletContext.setAttribute(PageRepositoryResource.PAGE_REPOSITORY_KEY, pop());
	}

	public void setBasePageRepository(PageRepositoryResource pageRepository) {
		this.pageRepository = pageRepository;
	}
	
}
